import Base from "../base.js";
import schedulesApi from '../../api/schedules.js';
import cinemasApi from '../../api/cinemas.js';
import Seats from "./seats.js"
export default class extends Base {
  data = {
    // 当前页
    curPage: 1,
    //每页显示条数
    eachPage: 10,
    // 总条数
    total: 0,
    // 总页数
    maxPage: 0,
    rows: [],
    cinemas: [],
    cinemasId:"",
  }
  render() {
    this.$el.html(`
    <h1 style="text-align:center">排片列表</h1>
        <div id="toolbar" style="display:flex;">
          <div class="form-inline">
           <div>
             选择影院 <select name="city"  style="width:250px;height:36px;margin-bottom:10px;border-color:#e6e6e6;" class="cinemasId"></select>
            </div>
          </div>
        </div>
        <table id="demo" lay-filter="test" style="text-align: center;"></table>
        <div id="test1"></div>
        `)
    this.tableEle = layui.table;
    this.laypage = layui.laypage;
    this.city = $("select[name=city]");
    this.tableEle.render({
      elem: '#demo'
      , cols: [[ //表头
        { field: '_id', title: 'ID', width: 100, fixed: 'left' }
        , {
          field: 'movieId', title: '电影名称', width: 200, align: 'center',
          templet: res => {
            const movieId = res.movieId?.cname || "";
            return movieId
          }
        }
        , {
          field: 'cinemasId', title: '影院名称', width: 200,align: 'center',
          templet: res => {
            const cinemasId = res.cinemasId?.name || "";
            return cinemasId
          }
        }
        , {
          field: 'theaterId', title: '放映厅', width: 150,align: 'center',
          templet: res => {
            const theaterId = res.theaterId?.name || "";
            return theaterId
          }
        }
        , { field: 'showDate', title: '放映日期', width: 150 ,align: 'center',}
        , { field: 'showTime', title: '放映时间', width: 150 ,align: 'center',}
        , { field: 'price', title: '价格', width: 100,align: 'center', }
        , {
          field: '_id',
          title: '操作',
          align: 'center',
          fixed: 'right',
          templet: res => {
            const { _id } = res;
            return ` 
                        <a class="layui-btn layui-btn-xs" lay-event="edit"><i class="layui-icon"></i>修改</a>
                        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del"><i class="layui-icon"></i>删除</a>
                        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="setSeat">查看座位</a>
                        `
          }
        }
      ]]
    });
  }

  handle() {
    this.tableEle.on('tool(test)', obj => { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
      var data = obj.data; //获得当前行数据
      var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
       //获得当前行 tr 的 DOM 对象（如果有的话）
      if (layEvent === 'edit') { //修改
        layer.alert(`
            <form  class="layui-form" action="" style="width:350px">
              <div class="layui-form-item">
                <label class="layui-form-label" style="padding:10px 5px;">ID</label>
                <div class="layui-input-inline">
                    <input type="text" name="_id" value=${data._id} required lay-verify="required" autocomplete="off" class="layui-input" style="width:210px">
                </div>
              </div>
              <div class="layui-form-item">
                 <label class="layui-form-label" style="padding:10px 5px;">电影名称</label>
                 <div class="layui-input-inline">
                   <input type="text" name="movieId" value=${data.movieId._id} required lay-verify="required" autocomplete="off" class="layui-input" style="width:210px">
                 </div>
               </div>
              <div class="layui-form-item">
                 <label class="layui-form-label" style="padding:10px 5px;">影院名称</label>
                 <div class="layui-input-inline">
                   <input type="text" name="cinemasId" value=${data.cinemasId._id} required lay-verify="required" autocomplete="off" class="layui-input" style="width:210px">
                 </div>
              </div>
              <div class="layui-form-item">
                 <label class="layui-form-label" style="padding:10px 5px;">放映厅</label>
                 <div class="layui-input-inline">
                   <input type="text" name="theaterId" value=${data.theaterId._id} required lay-verify="required" autocomplete="off" class="layui-input" style="width:210px">
                </div>
              </div>
              <div class="layui-form-item">
                  <label class="layui-form-label" style="padding:10px 5px;">放映日期</label>
                  <div class="layui-input-inline">
                    <input type="text" name="showDate" value=${data.showDate} required lay-verify="required" autocomplete="off" class="layui-input" style="width:210px">
                  </div>
              </div>
              <div class="layui-form-item">
                  <label class="layui-form-label" style="padding:10px 5px;">放映时间</label>
                  <div class="layui-input-inline">
                    <input type="text" name="showTime" value=${data.showTime} required lay-verify="required" autocomplete="off" class="layui-input" style="width:210px">
                  </div>
              </div>
              <div class="layui-form-item">
                <label class="layui-form-label" style="padding:10px 5px;">价格</label>
                  <div class="layui-input-inline">
                    <input type="text" name="price" value=${data.price} required lay-verify="required" autocomplete="off" class="layui-input" style="width:210px">
                  </div>
              </div>
              <div class="layui-form-item">
                 <div class="layui-input-block">
                   <button class="layui-btn" lay-submit lay-filter="formModify">确定修改</button>
                 </div>
              </div>
            </form>
        `)
      } else if (layEvent === 'del') {
        //删除事件
        this.delete(data);
      }else if (layEvent === 'setSeat') {
        new Seats({el:".layui-body",obj})
      }
      ;
    });
    this.formele=layui.form;
    // 确定修改事件
    layui.form.on('submit(formModify)', (data) => {
      this.modify(data.field)
      return false;
    });

    // 根据影城id查询影城下的排片
    this.city.on("change", e => {
      this.data.cinemasId = e.target.value;
      this.search(this.data.cinemasId);
    });
  }

  async search(cinemasId) {
    this.data.rows = await schedulesApi.searchSchedules(cinemasId);
    this.data.total = this.data.rows.length;
    this.rerender();
}

  // 删除
  async delete(data) {
    const status = await schedulesApi.delete(data._id);
    this.getSchedulesList();
    if (status.n == 1) {
      layer.msg('删除成功', {
        icon: 1,
        time: 1500 //2秒关闭（如果不配置，默认是3秒）
      }, function () {
        location.hash = "#/info/schedules";
      });

    } else {
      layer.msg('删除失败', {
        icon: 1,
        time: 1500
      });
    }
  }

  // 修改
  async modify(data) {
    const status = await schedulesApi.modify(data);
    this.getSchedulesList();
    if (status.n == 1) {
      layer.msg('修改成功', {
        icon: 1,
        time: 1500 //2秒关闭（如果不配置，默认是3秒）
      }, function () {
        location.hash = "#/info/schedules";
      });

    } else {
      layer.msg('修改失败', {
        icon: 1,
        time: 1500
      });
    }
  }
  // 获取所有影院
  async getcinemas() {
    this.data.cinemas = await cinemasApi.getall();
    this.rerender()
  }
  
  rerender() {
    // 排片列表的渲染
    this.tableEle.reload('demo', {
      data: this.data.rows
    });
    this.laypage.render({
      elem: 'test1' //注意，这里的 test1 是 ID，不用加 # 号
      , count: this.data.total
      , limit: this.data.eachPage
      , limits: [10, 20, 30, 40, 50]
      , curr: this.data.curPage
      , layout: ['prev', 'page', 'next', 'count', 'limit']
      , jump: async (obj, first) => {
        if (!first) {
          this.data.curPage = obj.curr;
          this.data.eachPage = obj.limit;
          const { curPage, eachPage } = this.data;
          this.data = await schedulesApi.get({ curPage, eachPage });
          this.tableEle.reload('demo', {
            data: this.data.rows,
            limit: this.data.eachPage
          });
        }
      }
    });
        // 获取影院数据并显示在页面上
        const [currentCinema] = this.data.cinemas;
        console.log(currentCinema.name);
        const options = _.map(this.data.cinemas, item => {
          return ` <option value="${item._id}">${item.name}</option>`
        }).join("");
        this.city.html(options).val(currentCinema._id);
        this.data.cinemasId = currentCinema._id;
    
  }

 mounted() {
     this.getSchedulesList();
     this.getcinemas();

  }
  async getSchedulesList() {
    const { curPage, eachPage } = this.data;
    this.data = await schedulesApi.get({ curPage, eachPage });
    this.rerender();
  }

}